﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;

/// <summary>
///  模組: 網頁控制項處理 Module
///  作者: Adams <adams@netdb.com.tw>
///  修改: 2012-3-31
///  目的: 動態抓取網頁中所有控制項
///  參數: 網頁物件
/// </summary>
public class ControlUtil
{
    /// <summary>
    /// 抓取指定控制項中所有的子控制項
    /// 使用方式：var listOfControls = ControlUtil.FindControlsOfType<WebControl>(Page);
    /// </summary>
    /// <typeparam name="T">欲抓取之控制項型別</typeparam>
    /// <param name="ctlRoot">控制項物件</param>
    /// <returns>所有抓取到的控制項泛型</returns>
    public static List<T> FindControlsOfType<T>(Control ctlRoot) where T : Control
    {
        List<T> controlsFound = new List<T>();

        if (typeof(T).IsInstanceOfType(ctlRoot))
            controlsFound.Add((T)(object)ctlRoot);

        foreach (Control ctlTemp in ctlRoot.Controls)
        {
            controlsFound.AddRange(FindControlsOfType<T>(ctlTemp));
        }

        return controlsFound;
    }

    /// <summary>
    /// 抓取網頁中所有的控制項
    /// 使用方式：
    /// List<WebControl> allControls = new List<WebControl>();
    /// GetControlList<WebControl>(Page.Controls, allControls);
    /// </summary>
    /// <typeparam name="T">控制項型別</typeparam>
    /// <param name="controlCollection">欲抓取之控制項集合</param>
    /// <param name="resultCollection">所有抓取到的控制項泛型</param>
    private static void GetControlList<T>(ControlCollection controlCollection, List<T> resultCollection) where T : Control
    {
        foreach (Control control in controlCollection)
        {
            if (control.ID != null)
            {
                //if (control.GetType() == typeof(T))
                if (control is T) // This is cleaner
                    resultCollection.Add((T)control);
            }
            if (control.HasControls())
                GetControlList(control.Controls, resultCollection);
        }
    }

}